<template>
  <div class="home-container">
    <el-container>
      <!-- 侧边栏 -->
      <el-aside width="64px" class="sidebar">
        <div class="sidebar-header" @click="toBack">
          <img src="../assets/police.png" alt="" />
        </div>
      </el-aside>
      <el-main class="chat-area">
        <div v-if="showWelcome" class="welcome-container">
          <div class="welcome-content">
            <div class="welcome-image">
              <img src="../assets/police.png" alt="" />
            </div>
            <h1 class="welcome-title">欢迎使用古塔分局数字警察</h1>
            <p class="welcome-subtitle">
              我可以帮助你解答各种问题,请选择你需要的服务
            </p>

            <div class="welcome-features">
              <div
                class="feature-card"
                v-for="(feature, index) in features"
                :key="index"
                @click="handleFeatureClick(feature)"
              >
                <el-icon :size="24" class="feature-icon"
                  ><component :is="feature.icon"
                /></el-icon>
                <h3>{{ feature.title }}</h3>
                <p>{{ feature.desc }}</p>
              </div>
            </div>
          </div>

          <div class="welcome-input">
            <el-input
              v-model="inputMessage"
              placeholder="输入消息..."
              @keyup.enter="handleEnter"
              size="large"
              type="textarea"
              :rows="3"
              resize="none"
              class="centered-input"
            />
            <el-button
              @click="isStreaming ? stopStreaming() : sendMessage()"
              type="primary"
              class="send-button"
            >
              <el-icon v-if="!isSending && !isStreaming"><Promotion /></el-icon>
              <el-icon v-else-if="isStreaming"><VideoPause /></el-icon>
              <el-icon v-else><Loading /></el-icon>
            </el-button>
          </div>
        </div>

        <div
          v-else
          style="
            height: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
          "
        >
          <div class="chat-header" v-if="isBusinessChat">
            <div class="current-chat-title">
              <el-icon
                ><component
                  :is="features.find((f) => f.title == currentChatTitle)?.icon"
              /></el-icon>
              <h3>{{ currentChatTitle }}</h3>
            </div>
          </div>
          <div class="chat-container-wrapper">
            <el-scrollbar class="message-scroll">
              <div class="chat-container">
                <div
                  v-for="(message, index) in messages"
                  :key="index"
                  class="message-container"
                  :class="{ 'user-message-container': message.role == 'user' }"
                >
                  <img
                    class="message-container-img"
                    v-if="message.role == 'user'"
                    src="../assets/user.jpg"
                    alt=""
                    style="margin-left: 10px"
                  />
                  <img
                    class="message-container-img"
                    v-else
                    src="../assets/police.png"
                    alt=""
                    style="margin-right: 10px"
                  />
                  <div
                    class="message"
                    :class="{ 'user-message': message.role === 'user' }"
                  >
                    <!-- <div class="message-content">
                      <div
                        class="message-text"
                        v-html="formatMessageContent(message.content)"
                      ></div>
                      <div class="message-time">{{ formatTime() }}</div> 
                    </div> -->
                    <div class="message-content">
                      <div class="message-text">
                        <!-- 当 AI 正在生成回复时显示加载图标 -->
                        <el-icon
                          v-if="
                            message.role == 'assistant' && message.isLoading
                          "
                          class="loading-icon"
                        >
                          <Loading />
                        </el-icon>
                        <div
                          v-else
                          v-html="formatMessageContent(message.content)"
                        ></div>
                      </div>
                      <div class="message-time">
                        {{ formatMessageTime(message.timestamp) }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </el-scrollbar>
          </div>

          <div class="input-area">
            <el-input
              v-model="inputMessage"
              placeholder="输入消息..."
              @keyup.enter="handleEnter"
              size="large"
              class="message-input"
              type="textarea"
              :rows="3"
              resize="none"
            >
            </el-input>
            <el-button
              @click="isStreaming ? stopStreaming() : sendMessage()"
              type="primary"
              class="send-message"
            >
              <el-icon v-if="!isSending && !isStreaming"><Promotion /></el-icon>
              <el-icon v-else-if="isStreaming"><VideoPause /></el-icon>
              <el-icon v-else><Loading /></el-icon>
            </el-button>
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { Promotion, Loading, VideoPause } from "@element-plus/icons-vue";

// import { ArrowLeft,ArrowRight  } from "@element-plus/icons-vue";
import { userApi } from "@/api/api";

export default {
  // components: { ArrowLeft,ArrowRight },
  components: { Promotion, Loading, VideoPause },
  name: "HomePage",
  data() {
    return {
      user: {
        name: "用户名",
        avatar: "../assets/police.png",
      },
      messages: [
        {
          role: "assistant",
          content: "你好！我是AI助手，有什么可以帮你的吗？",
          isLoading: false, // 新增属性
        },
      ],
      chatHistory: [], // 添加这行初始化
      inputMessage: "",
      currentChatId: null,
      currentChatTitle: "",
      conversation_id: "", // 会话id
      isSending: false, // 新增发送状态
      showWelcome: true,
      features: [
        {
          icon: "MagicStick",
          title: "户籍办理",
          desc: "户籍办理业务选我",
          id: 1,
        },
        {
          icon: "Connection",
          title: "企业服务",
          desc: "企业审批相关业务选我",
          id: 2,
        },
        {
          icon: "ChatLineRound",
          title: "警务问答",
          desc: "咨询警务知识选我",
          id: 3,
        },
      ],
      isStreaming: false, // 新增流式响应状态
      messageVersion: 0, // 新增版本控制
      user_id: null,
      isBusinessChat: false, // 新增标志位
    };
  },
  mounted() {
    this.getUid();
  },
  methods: {
    stopStreaming() {
      this.isStreaming = false;
      this.isSending = false;
    },
    formatTime() {
      // return new Date().toLocaleTimeString([], {
      //   hour: "2-digit",
      //   minute: "2-digit",
      // });
      return new Date().toLocaleTimeString([], {
        hour: "2-digit",
        minute: "2-digit",
      });
    },
    formatMessageContent(content) {
      // 处理Markdown格式的加粗和列表
      let formatted = content
        .replace(/###+\s+(.*?)\n/g, "<h3>$1</h3>") // 处理###标题
        .replace(/\*\*(.*?)\*\*/g, "<strong>$1</strong>"); // 加粗文本

      // 原有think标签处理逻辑
      let buffer = "";
      let inThinkTag = false;
      let result = "";

      for (let i = 0; i < formatted.length; i++) {
        const char = formatted[i];

        if (char === "<" && formatted.substr(i, 6) === "<think") {
          inThinkTag = true;
          buffer = "";
          i += 6;
          continue;
        }

        if (
          inThinkTag &&
          char === "<" &&
          formatted.substr(i, 8) === "</think>"
        ) {
          if (buffer.trim()) {
            result += `<div class="think-content">${buffer}</div>`;
          }
          inThinkTag = false;
          i += 7;
          continue;
        }

        if (inThinkTag) {
          buffer += char;
        } else {
          result += char;
        }
      }

      if (inThinkTag && buffer.trim()) {
        result += `<div class="think-content">${buffer}</div>`;
      }

      return result;
    },
    formatMessageTime(timestamp) {
      if (!timestamp) return "";
      return new Date(timestamp).toLocaleTimeString([], {
        hour: "2-digit",
        minute: "2-digit",
      });
    },
    startNewChat() {
      this.currentChatId = Date.now();
      this.messages = [
        {
          role: "assistant",
          content: "你好！我是AI助手，有什么可以帮你的吗？",
        },
      ];
      this.chatHistory.unshift({
        id: this.currentChatId,
        title: `新对话 ${this.chatHistory.length + 1}`,
      });
      this.isBusinessChat = false; // 新增标志位
      this.currentChatTitle = ""; // 清空业务标题
    },
    loadChat(chatId) {
      this.currentChatId = chatId;
      // 这里应该加载对应聊天记录
      this.messages = [
        { role: "assistant", content: `这是对话 ${chatId} 的历史记录` },
      ];
    },
    async sendMessage() {
      if (!this.inputMessage.trim()) return;

      this.isSending = true; // 开始发送

      if (this.showWelcome) {
        this.showWelcome = false;
        this.startNewChat();
      }

      // 添加用户消息
      this.messages.push({
        role: "user",
        content: this.inputMessage,
        isLoading: false, // 设置为正在加载
        timestamp: new Date(), // 记录时间戳
      });

      // 添加AI消息占位
      let aiMessage = {
        role: "assistant",
        content: "",
        isLoading: true, // 设置为正在加载
        timestamp: null, // 初始化为 null，流式响应结束后设置
      };

      this.messages.push(aiMessage);
      const aiMessageIndex = this.messages.length - 1; // 记录 AI 消息的索引
      try {
        const params = new URLSearchParams();
        params.append("message", this.inputMessage);
        params.append("user_id", this.user_id);
        // 如果是业务聊天，添加业务类型参数
        if (this.isBusinessChat) {
          let feature = this.features.find(
            (f) => f.title == this.currentChatTitle
          );
          if (feature) {
            params.append("rag_id", feature.id);
          }
        } else {
          params.append("rag_id", 0);
        }
        console.log(params, "params");

        const response = await fetch("http://localhost/api/chat", {
          method: "POST",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            Accept: "text/event-stream", // 添加流式响应支持
            "Cache-Control": "no-cache", // 禁用缓存
            Connection: "keep-alive", // 保持连接
          },
          body: params,
        });
        this.inputMessage = "";

        // 检查响应是否有效
        if (!response.ok || !response.body) {
          throw new Error(`请求失败: ${response.status}`);
        }

        const reader = response.body.getReader();
        const decoder = new TextDecoder("utf-8"); // 明确指定编码
        // 添加流式接收状态
        this.isStreaming = true;
        while (this.isStreaming) {
          const { done, value } = await reader.read();
          if (done) {
            this.isStreaming = false;
            console.log("====================================");
            console.log(this.messages);
            console.log("====================================");
            this.messages[aiMessageIndex].timestamp = new Date();
            break;
          }
          this.messages[aiMessageIndex].isLoading = false;
          const chunk = decoder.decode(value, { stream: true });
          aiMessage.content += chunk;
          this.messageVersion++; // 触发更新
          // this.$forceUpdate();
          // 滚动到底部
          this.$nextTick(() => {
            this.messages = [...this.messages]; // 创建新数组触发响应式更新
            const scrollContainer = this.$el.querySelector(
              ".message-scroll .el-scrollbar__wrap"
            );
            if (scrollContainer) {
              scrollContainer.scrollTop = scrollContainer.scrollHeight;
            }
          });
        }
      } catch (error) {
        console.error("请求失败:", error);
        this.messages[aiMessageIndex].isLoading = false;
        this.messages[aiMessageIndex].timestamp = new Date();
        aiMessage.content =
          "连接服务失败，请检查: \n1. 后端服务是否运行 \n2. 网络连接是否正常";
        this.$forceUpdate();
      } finally {
        this.isSending = false;
        // this.inputMessage = "";
        this.isStreaming = false;
      }
    },

    handleEnter(e) {
      if (e.ctrlKey || e.shiftKey) {
        // 按下Ctrl或Shift+Enter时换行
        this.inputMessage += "\n";
      } else {
        // 单独按下Enter时发送消息
        this.sendMessage();
        e.preventDefault(); // 阻止默认换行行为
      }
    },
    toBack() {
      // 重置所有状态和数据
      this.messages = [
        {
          role: "assistant",
          content: "你好！我是AI助手，有什么可以帮你的吗？",
        },
      ];
      this.inputMessage = "";
      this.currentChatId = null;
      this.currentChatTitle = "";
      this.conversation_id = "";
      this.isSending = false;
      this.showWelcome = true;
      this.isStreaming = false;
      this.messageVersion = 0;
      this.chatHistory = [];
    },
    async getUid() {
      try {
        const res = await userApi.getUid();
        console.log(res);
        this.user_id = res;
      } catch (error) {
        console.error("获取用户ID失败:", error);
      }
    },
    handleFeatureClick(feature) {
      console.log(feature);
      this.user = {
        name: feature.title,
        avatar: "../assets/police.png",
      };

      // 设置当前对话标题
      this.currentChatTitle = feature.title;

      // 隐藏欢迎界面
      this.showWelcome = false;

      // 初始化对话消息
      this.messages = [
        {
          role: "assistant",
          content: `您好！这里是${feature.title}服务，请问有什么可以帮您？`,
        },
      ];

      // 创建新的对话ID
      this.currentChatId = Date.now();

      this.isBusinessChat = true; // 新增标志位
    },
  },
};
</script>

<style scoped>
.home-container {
  height: 100vh;
  background-color: #f8fafc;
}
.sidebar {
  /* background-color: #ffffff; */
  background-color: #f9fbff;
  height: 100vh;
  border-right: 1px solid #e5e7eb;
  box-shadow: 2px 0 10px rgba(0, 0, 0, 0.05);
}
.user-info {
  display: flex;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e5e7eb;
  img {
    width: 50px;
    height: 50px;
    border-radius: 50%;
  }
}
.user-details {
  margin-left: 12px;
  display: flex;
  flex-direction: column;
}
.username {
  font-weight: 600;
  color: #1f2937;
}
.user-status {
  font-size: 12px;
  color: #6b7280;
}

.new-chat-btn {
  width: 90%;
  margin: 15px auto;
  font-weight: 500;
  margin-left: 10px;
}

.history-title {
  padding: 10px 20px;
  font-size: 14px;
  color: #6b7280;
  font-weight: 500;
}

.history-scroll {
  height: calc(100vh - 200px);
}

.history-menu {
  border-right: none;
}

.history-menu .el-menu-item {
  height: 50px;
  line-height: 50px;
  margin: 0 10px;
  border-radius: 8px;
}

.history-menu .el-menu-item:hover {
  background-color: #f3f4f6;
}

.active-chat {
  background-color: #e0e7ff !important;
  color: #4f46e5;
}

/* .chat-header {
  padding: 15px 20px;
  border-bottom: 1px solid #e5e7eb;
  background-color: #ffffff;
}

.chat-header h3 {
  margin: 0;
  font-size: 16px;
  color: #1f2937;
} */

.current-chat-title {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 15px 20px;
  background-color: #f8fafc;
  border-bottom: 1px solid #e5e7eb;
}

.current-chat-title h3 {
  margin: 0;
  font-size: 18px;
  color: #4f46e5;
  font-weight: 600;
}

.current-chat-title .el-icon {
  font-size: 20px;
  color: #4f46e5;
}

.chat-header {
  background-color: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.chat-container-wrapper {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.message-scroll {
  flex: 1;
  margin-bottom: 0;
  height: 100%;
  /deep/ .el-scrollbar__wrap {
    overflow-x: hidden;
  }
}

.chat-area {
  display: flex;
  flex-direction: column;
  height: 100vh;
  padding: 0;
  background-color: #f9fafb;
  position: relative;
  overflow: hidden;
}

.chat-container {
  padding: 20px;
  min-height: 100%;
  box-sizing: border-box;
}

.message {
  margin-bottom: 20px;
  max-width: 75%;
}

.message-content {
  display: inline-block;
  padding: 12px 16px;
  border-radius: 12px;
  background-color: #ffffff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.user-message .message-content {
  background-color: #4f46e5;
  color: white;
}

.message-time {
  font-size: 12px;
  color: #9ca3af;
  margin-top: 4px;
  text-align: right;
}

.user-message .message-time {
  color: rgba(255, 255, 255, 0.7);
}

.input-area {
  padding: 20px;
  background-color: #ffffff;
  border-top: 1px solid #e5e7eb;
  position: sticky;
  bottom: 0;
  z-index: 10;
  display: flex;
}
.send-message {
  width: 80px;
  height: 100%;
  border-radius: 0 20px 20px 0;
}

.message-input {
  border-radius: 20px 0 0 20px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
.message-input:deep(.el-textarea__inner) {
  padding: 15px 10px;
  border-radius: 20px 0 0 20px;
  box-sizing: border-box;
}

.message-container {
  display: flex;
  /* margin-bottom: 20px; */
  max-width: 80%;
  align-items: flex-start;
}
.message-container-img {
  width: 36px;
  border-radius: 50%;
}

.user-message-container {
  margin-left: auto;
  flex-direction: row-reverse;
}

.message-avatar {
  margin: 0 12px;
}

.message {
  max-width: calc(100% - 60px);
}

.message-content {
  padding: 12px 16px;
  border-radius: 18px;
  background-color: #ffffff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  position: relative;
}

.user-message .message-content {
  background-color: #4f46e5;
  color: white;
}
.message-text {
  white-space: pre-wrap;

  h3 {
    font-size: 1.2em;
    font-weight: bold;
    margin: 15px 0 10px;
    color: #333;
  }

  strong {
    font-weight: bold;
    color: inherit;
  }

  li {
    display: list-item;
    margin-left: 20px;
    padding-left: 5px;
    list-style-type: disc;
  }
}

:deep(.think-content) {
  color: #9ca3af;
  font-style: italic;
  display: block;
  margin: 5px 0;
  background-color: #f3f4f6;
  padding: 8px 12px;
  border-radius: 6px;
  font-size: 0.9em;
}
.sidebar-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px;
  cursor: pointer;
  border-bottom: 1px solid #e5e7eb;
}

.sidebar-header img {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}

.collapse-icon {
  font-size: 18px;
  color: #666;
}

/* 调整折叠状态下的样式 */
.sidebar {
  transition: width 0.3s ease;
}

.history-menu .el-menu-item {
  height: 50px;
  line-height: 50px;
  margin: 0 10px;
  border-radius: 8px;
  white-space: nowrap;
  overflow: hidden;
}
.welcome-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  padding: 20px;
  background-color: #f9fafb;
}

.welcome-content {
  text-align: center;
  max-width: 800px;
  margin-bottom: 40px;
}

.welcome-image {
  width: 80px;
  /* height: 80px; */
  margin: auto;
  img {
    width: 100%;
    height: 100%;
    border-radius: 50%;
  }
}

.welcome-title {
  font-size: 32px;
  color: #1f2937;
  margin: 20px 0 10px;
  font-weight: 600;
}

.welcome-subtitle {
  font-size: 16px;
  color: #6b7280;
  margin-bottom: 40px;
}

.welcome-features {
  display: flex;
  justify-content: center;
  gap: 30px;
  margin: 40px 0;
}

.feature-card {
  background: white;
  border-radius: 12px;
  padding: 25px;
  width: 220px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s, box-shadow 0.3s;
}

.feature-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 15px rgba(0, 0, 0, 0.1);
}

.feature-icon {
  color: #4f46e5;
  margin-bottom: 15px;
}

.feature-card h3 {
  font-size: 18px;
  color: #1f2937;
  margin: 10px 0;
}

.feature-card p {
  font-size: 14px;
  color: #6b7280;
  line-height: 1.5;
}

.welcome-input {
  width: 100%;
  max-width: 800px;
  margin-top: 30px;
  display: flex;
}
.centered-input {
  border-radius: 20px 0 0 20px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
.centered-input:deep(.el-textarea__inner) {
  padding: 15px 10px;
  border-radius: 20px 0 0 20px;
  box-sizing: border-box;
}
.send-button {
  width: 70px;
  border-radius: 0 20px 20px 0;
  height: 100%;
}
.loading-icon {
  animation: spin 1s linear infinite;
  font-size: 20px;
  color: #4f46e5;
  margin-right: 10px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
